<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>商家信息调试工具</title>
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
            padding: 20px;
            background-color: #f5f5f5;
        }
        .container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .section {
            margin-bottom: 30px;
            padding: 15px;
            border: 1px solid #e0e0e0;
            border-radius: 5px;
        }
        .section h3 {
            margin-top: 0;
            color: #333;
            border-bottom: 2px solid #0097FF;
            padding-bottom: 5px;
        }
        .form-group {
            margin-bottom: 15px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        input, select, button {
            padding: 8px 12px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
        }
        input[type="text"], input[type="number"] {
            width: 300px;
        }
        button {
            background-color: #0097FF;
            color: white;
            cursor: pointer;
            border: none;
            margin-right: 10px;
        }
        button:hover {
            background-color: #0080dd;
        }
        .result {
            margin-top: 15px;
            padding: 10px;
            border-radius: 4px;
            font-family: monospace;
            white-space: pre-wrap;
            max-height: 400px;
            overflow-y: auto;
        }
        .success {
            background-color: #d4edda;
            border: 1px solid #c3e6cb;
            color: #155724;
        }
        .error {
            background-color: #f8d7da;
            border: 1px solid #f5c6cb;
            color: #721c24;
        }
        .info {
            background-color: #d1ecf1;
            border: 1px solid #bee5eb;
            color: #0c5460;
        }
        .business-preview {
            display: grid;
            grid-template-columns: auto 1fr;
            gap: 10px;
            margin-top: 10px;
        }
        .business-preview img {
            width: 80px;
            height: 60px;
            object-fit: cover;
            border-radius: 4px;
        }
        .food-list {
            display: grid;
            gap: 10px;
            margin-top: 10px;
        }
        .food-item {
            display: grid;
            grid-template-columns: auto 1fr auto;
            gap: 10px;
            padding: 10px;
            border: 1px solid #e0e0e0;
            border-radius: 4px;
        }
        .food-item img {
            width: 60px;
            height: 60px;
            object-fit: cover;
            border-radius: 4px;
        }
    </style>
</head>
<body>
<div class="container">
    <h1>🍽️ 商家信息调试工具</h1>

    <div class="section">
        <h3>📝 配置</h3>
        <div class="form-group">
            <label for="baseUrl">后端服务地址:</label>
            <input type="text" id="baseUrl" value="http://localhost:8080/elm">
        </div>
        <div class="form-group">
            <label for="businessId">商家ID:</label>
            <input type="number" id="businessId" value="10008">
        </div>
    </div>

    <div class="section">
        <h3>🏪 商家信息测试</h3>
        <button onclick="testBusinessInfo()">获取商家信息</button>
        <button onclick="clearBusinessResult()">清空结果</button>
        <div id="businessResult" class="result info" style="display: none;"></div>
        <div id="businessPreview"></div>
    </div>

    <div class="section">
        <h3>🍕 食品列表测试</h3>
        <button onclick="testFoodList()">获取食品列表</button>
        <button onclick="clearFoodResult()">清空结果</button>
        <div id="foodResult" class="result info" style="display: none;"></div>
        <div id="foodPreview"></div>
    </div>

    <div class="section">
        <h3>🔄 综合测试</h3>
        <button onclick="testAll()">测试所有API</button>
        <button onclick="simulateBusinessPage()">模拟商家页面加载</button>
        <div id="allResult" class="result info" style="display: none;"></div>
    </div>
</div>

<script>
    const apiUrl = () => document.getElementById('baseUrl').value;
    const businessId = () => document.getElementById('businessId').value;

    // 测试商家信息API
    async function testBusinessInfo() {
        const resultDiv = document.getElementById('businessResult');
        const previewDiv = document.getElementById('businessPreview');

        resultDiv.style.display = 'block';
        resultDiv.className = 'result info';
        resultDiv.textContent = '正在获取商家信息...';
        previewDiv.innerHTML = '';

        try {
            const formData = new FormData();
            formData.append('businessId', businessId());

            const response = await fetch(`${apiUrl()}/BusinessController/getBusinessById`, {
                method: 'POST',
                body: formData
            });

            const responseText = await response.text();

            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${responseText}`);
            }

            let data;
            try {
                data = JSON.parse(responseText);
            } catch (e) {
                throw new Error(`响应不是有效的JSON: ${responseText}`);
            }

            resultDiv.className = 'result success';
            resultDiv.textContent = JSON.stringify(data, null, 2);

            // 显示商家信息预览
            if (data && typeof data === 'object') {
                previewDiv.innerHTML = `
                        <div class="business-preview">
                            <img src="${data.businessImg || '/placeholder.png'}"
                                 alt="商家图片"
                                 onerror="this.src='/placeholder.png'">
                            <div>
                                <h4>${data.businessName || '未知商家'}</h4>
                                <p>起送价: ¥${data.starPrice || 0}</p>
                                <p>配送费: ¥${data.deliveryPrice || 0}</p>
                                <p>描述: ${data.businessExplain || '暂无描述'}</p>
                                <p>地址: ${data.businessAddress || '暂无地址'}</p>
                                ${data.rating ? `<p>评分: ${data.rating} ⭐</p>` : ''}
                                ${data.distance ? `<p>距离: ${data.distance}km</p>` : ''}
                                ${data.monthlySales ? `<p>月销量: ${data.monthlySales}</p>` : ''}
                            </div>
                        </div>
                    `;
            }

        } catch (error) {
            resultDiv.className = 'result error';
            resultDiv.textContent = `错误: ${error.message}`;
            console.error('获取商家信息失败:', error);
        }
    }

    // 测试食品列表API
    async function testFoodList() {
        const resultDiv = document.getElementById('foodResult');
        const previewDiv = document.getElementById('foodPreview');

        resultDiv.style.display = 'block';
        resultDiv.className = 'result info';
        resultDiv.textContent = '正在获取食品列表...';
        previewDiv.innerHTML = '';

        try {
            const formData = new FormData();
            formData.append('businessId', businessId());

            const response = await fetch(`${apiUrl()}/FoodController/listFoodByBusinessId`, {
                method: 'POST',
                body: formData
            });

            const responseText = await response.text();

            if (!response.ok) {
                throw new Error(`HTTP ${response.status}: ${responseText}`);
            }

            let data;
            try {
                data = JSON.parse(responseText);
            } catch (e) {
                throw new Error(`响应不是有效的JSON: ${responseText}`);
            }

            resultDiv.className = 'result success';
            resultDiv.textContent = JSON.stringify(data, null, 2);

            // 显示食品列表预览
            if (Array.isArray(data) && data.length > 0) {
                const foodItems = data.map(food => `
                        <div class="food-item">
                            <img src="${food.foodImg || '/placeholder.png'}"
                                 alt="${food.foodName}"
                                 onerror="this.src='/placeholder.png'">
                            <div>
                                <h5>${food.foodName || '未知食品'}</h5>
                                <p>${food.foodExplain || '暂无描述'}</p>
                            </div>
                            <div>
                                <strong>¥${food.foodPrice || 0}</strong>
                            </div>
                        </div>
                    `).join('');

                previewDiv.innerHTML = `
                        <h4>食品列表 (${data.length}个)</h4>
                        <div class="food-list">${foodItems}</div>
                    `;
            } else if (Array.isArray(data)) {
                previewDiv.innerHTML = '<p>该商家暂无食品</p>';
            }

        } catch (error) {
            resultDiv.className = 'result error';
            resultDiv.textContent = `错误: ${error.message}`;
            console.error('获取食品列表失败:', error);
        }
    }

    // 综合测试
    async function testAll() {
        const resultDiv = document.getElementById('allResult');
        resultDiv.style.display = 'block';
        resultDiv.className = 'result info';
        resultDiv.textContent = '开始综合测试...\n';

        try {
            // 测试商家信息
            resultDiv.textContent += '1. 测试商家信息API...\n';
            const businessResponse = await fetch(`${apiUrl()}/BusinessController/getBusinessById`, {
                method: 'POST',
                body: (() => {
                    const fd = new FormData();
                    fd.append('businessId', businessId());
                    return fd;
                })()
            });

            const businessText = await businessResponse.text();
            const businessData = JSON.parse(businessText);
            resultDiv.textContent += `   ✅ 商家信息获取成功: ${businessData.businessName}\n`;

            // 测试食品列表
            resultDiv.textContent += '2. 测试食品列表API...\n';
            const foodResponse = await fetch(`${apiUrl()}/FoodController/listFoodByBusinessId`, {
                method: 'POST',
                body: (() => {
                    const fd = new FormData();
                    fd.append('businessId', businessId());
                    return fd;
                })()
            });

            const foodText = await foodResponse.text();
            const foodData = JSON.parse(foodText);
            resultDiv.textContent += `   ✅ 食品列表获取成功: ${foodData.length}个食品\n`;

            resultDiv.textContent += '\n🎉 所有测试通过！';
            resultDiv.className = 'result success';

        } catch (error) {
            resultDiv.textContent += `\n❌ 测试失败: ${error.message}`;
            resultDiv.className = 'result error';
        }
    }

    // 模拟商家页面加载
    async function simulateBusinessPage() {
        const resultDiv = document.getElementById('allResult');
        resultDiv.style.display = 'block';
        resultDiv.className = 'result info';
        resultDiv.textContent = '模拟BusinessInfo.vue页面加载...\n';

        try {
            const bId = businessId();

            if (!bId) {
                throw new Error('商家ID缺失');
            }

            resultDiv.textContent += `商家ID: ${bId}\n`;
            resultDiv.textContent += '用户信息: 模拟已登录用户\n\n';

            // 并行请求
            resultDiv.textContent += '并行发送API请求...\n';

            const [businessResponse, foodResponse] = await Promise.all([
                fetch(`${apiUrl()}/BusinessController/getBusinessById`, {
                    method: 'POST',
                    body: (() => {
                        const fd = new FormData();
                        fd.append('businessId', bId);
                        return fd;
                    })()
                }),
                fetch(`${apiUrl()}/FoodController/listFoodByBusinessId`, {
                    method: 'POST',
                    body: (() => {
                        const fd = new FormData();
                        fd.append('businessId', bId);
                        return fd;
                    })()
                })
            ]);

            // 处理商家信息响应
            const businessText = await businessResponse.text();
            resultDiv.textContent += `商家信息API响应状态: ${businessResponse.status}\n`;

            let businessData;
            try {
                businessData = JSON.parse(businessText);
                resultDiv.textContent += '商家信息解析成功\n';
            } catch (e) {
                throw new Error(`商家信息JSON解析失败: ${businessText}`);
            }

            // 处理食品列表响应
            const foodText = await foodResponse.text();
            resultDiv.textContent += `食品列表API响应状态: ${foodResponse.status}\n`;

            let foodData;
            try {
                foodData = JSON.parse(foodText);
                resultDiv.textContent += '食品列表解析成功\n';
            } catch (e) {
                throw new Error(`食品列表JSON解析失败: ${foodText}`);
            }

            // 模拟Vue组件的数据赋值逻辑
            resultDiv.textContent += '\n模拟Vue组件数据赋值:\n';

            if (businessData && typeof businessData === 'object') {
                resultDiv.textContent += `✅ business 对象赋值成功\n`;
                resultDiv.textContent += `   - businessName: ${businessData.businessName || 'undefined'}\n`;
                resultDiv.textContent += `   - businessImg: ${businessData.businessImg || 'undefined'}\n`;
                resultDiv.textContent += `   - starPrice: ${businessData.starPrice || 'undefined'}\n`;
            } else {
                resultDiv.textContent += `❌ business 对象赋值失败: ${typeof businessData}\n`;
            }

            if (Array.isArray(foodData)) {
                resultDiv.textContent += `✅ foodArr 数组赋值成功: ${foodData.length}个食品\n`;
                if (foodData.length > 0) {
                    resultDiv.textContent += `   - 第一个食品: ${foodData[0].foodName || 'undefined'}\n`;
                }
            } else {
                resultDiv.textContent += `❌ foodArr 数组赋值失败: ${typeof foodData}\n`;
            }

            // 检查渲染条件
            resultDiv.textContent += '\n渲染条件检查:\n';
            resultDiv.textContent += `v-if="business": ${businessData ? '✅ true' : '❌ false'}\n`;
            resultDiv.textContent += `v-if="business && business.businessImg": ${(businessData && businessData.businessImg) ? '✅ true' : '❌ false'}\n`;
            resultDiv.textContent += `v-if="business && business.businessName": ${(businessData && businessData.businessName) ? '✅ true' : '❌ false'}\n`;
            resultDiv.textContent += `v-if="foodArr && foodArr.length > 0": ${(Array.isArray(foodData) && foodData.length > 0) ? '✅ true' : '❌ false'}\n`;

            resultDiv.className = 'result success';
            resultDiv.textContent += '\n🎉 页面加载模拟完成！';

        } catch (error) {
            resultDiv.textContent += `\n❌ 模拟失败: ${error.message}`;
            resultDiv.className = 'result error';
            console.error('页面加载模拟失败:', error);
        }
    }

    // 清空结果
    function clearBusinessResult() {
        document.getElementById('businessResult').style.display = 'none';
        document.getElementById('businessPreview').innerHTML = '';
    }

    function clearFoodResult() {
        document.getElementById('foodResult').style.display = 'none';
        document.getElementById('foodPreview').innerHTML = '';
    }

    // 页面加载时显示提示
    window.onload = function() {
        console.log('商家信息调试工具已加载');
        console.log('使用说明：');
        console.log('1. 确保后端服务正在运行');
        console.log('2. 输入正确的商家ID');
        console.log('3. 点击各个测试按钮进行调试');
    };
</script>
</body>
</html>